package router

import (
	"net/http"
	"cloud_worm/util/uhttp"
	"github.com/golang/glog"
	"fmt"
	"cloud_worm/util/uratelimit"
)

/**
 请求所有的配置
 http://www.xxx.com:8080/api/all
 */
func ConfigAll(rw http.ResponseWriter, req *http.Request) {

	req.ParseForm()

	RouteSrvMap.mux.Lock()
	versionConfig := RouteSrvMap.ServerConfig
	RouteSrvMap.mux.Unlock()

	responData := uhttp.ResponData{Code: uhttp.RespCodeOk, Msg: "OK", Data: versionConfig}
	responData.SendResponse(rw)

	return
}

const (
	UriConfigApi = "/api/config.json"
	RateBucket = 100
	MaxBucketCnt = 100
)

/**
 请求指定版本号
 http://www.xxx.com:8080/api/config.json?version=100100101
 */
func ConfigApi(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()

	version, found1 := req.Form["version"]
	if !found1 {
		glog.Errorf("No input agent version: %s", req.RemoteAddr)

		responData := uhttp.ResponData{Code: uhttp.RespCodeParamErr, Msg: "No input agent version"}
		responData.SendResponse(rw)
		return
	}

	limit, err := uratelimit.GetTokenBucket(UriConfigApi)
	if err != nil {
		glog.Errorf(err.Error())

		responData := uhttp.ResponData{Code: uhttp.RespCodeSystemErr, Msg: err.Error()}
		responData.SendResponse(rw)
		return
	}
	avai := limit.Allow()
	if avai == false {
		glog.Errorf("too fast request for rate:%d/s and First:%d", RateBucket, MaxBucketCnt)

		responData := uhttp.ResponData{Code: uhttp.RespCodeTooFast, Msg: fmt.Sprintf("too fast request for rate:%d/s and First:%d", RateBucket, MaxBucketCnt)}
		responData.SendResponse(rw)
		return
	}

	RouteSrvMap.mux.Lock()
	versionConfig, exist := RouteSrvMap.ServerConfig[string(version[0])]
	RouteSrvMap.mux.Unlock()

	// todo: 增加一个服务检测，起到httpdns的作用

	if exist {
		responData := uhttp.ResponData{Code: uhttp.RespCodeOk, Msg: "OK", Data: versionConfig}
		responData.SendResponse(rw)
	} else {
		responData := uhttp.ResponData{Code: uhttp.RespCodeParamErr, Msg: "No this version config"}
		responData.SendResponse(rw)
	}

	return
}